using System.Diagnostics;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace Fusion.Protobuf.Editor
{
    public class ProtobufGenerator
    {
        private static string protoPath = $"{Path.GetFullPath("Protobuf")}";
        private static string protoCSharpPath = $"{Application.dataPath}/Scripts/Protobuf";
#if FUSION_FRAMEWORK_PROJECT
        private static string protoGeneratorPath = $"{Application.dataPath}/com.fusion.protobuf/Editor/Protobuf-23.3/Generate.bat";
#else
        private static string protoGeneratorPath = $"{Path.GetFullPath("Packages/com.fusion.protobuf")}/Editor/Protobuf-23.3/Generate.bat";
#endif

        [MenuItem("Protobuf/Generate/CSharp", false, 100)]
        public static void GenerateProtobufCSharp()
        {
            GenerateProtobuf("CSharp");
        }

        public static void GenerateProtobuf(string type)
        {
            if (!Directory.Exists(protoPath))
            {
                UnityEngine.Debug.Log($"{protoPath} is not exist, please create!");
                return;
            }

            GenerateProtobuf(type, protoPath, protoCSharpPath);
        }

        public static void GenerateProtobuf(string type, string source, string destination)
        {
            Process p = new Process();
            p.StartInfo.Arguments = $"{source} {destination}";
            p.StartInfo.Arguments = p.StartInfo.Arguments.Replace("/", "\\");
            p.StartInfo.FileName = protoGeneratorPath;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            StreamReader sOut = p.StandardOutput;
            StreamReader sError = p.StandardError;
            p.WaitForExit();
            p.Close();
            string results = sOut.ReadToEnd().Trim();
            string errors = sError.ReadToEnd().Trim();
            UnityEngine.Debug.Log(results);
            if (errors != null && errors != "")
            {
                UnityEngine.Debug.LogError(errors);
            }
            AssetDatabase.Refresh();
        }
    }
}
